﻿namespace JobButenko.Models
{
    using System;
    using System.Web.Security;

    using JobButenko.App_Data;
    using JobButenko.Models.BusinessLogicLayer;

    public static class AccountModel
    {
        private static IFormsAuthenticationService formService;

        private static IFormsAuthenticationService FormsService
        {
            get { return formService ?? (formService = new FormsAuthenticationService()); }
        }

        public static bool LogOn(string username, string password)
        {
            var dataManager = new DataManager();

            if (dataManager.User.ValidateUser(username, password))
            {
                FormsService.SignIn(username, true);
                return true;
            }

            return false;
        }

        public static void LogOff()
        {
            FormsService.SignOut();
        }
    }

    public interface IRoleService
    {
        bool IsUserInRole(string username, string rolename);
    }

    public class AccountRoleService : IRoleService
    {
        private readonly RoleProvider provider;

        public AccountRoleService()
            : this(null)
        {
        }

        private AccountRoleService(RoleProvider provider)
        {
            this.provider = provider ?? new MyRoleProvider();
        }

        public bool IsUserInRole(string username, string rolename)
        {
            return this.provider.IsUserInRole(username, rolename);
        }
    }

    public interface IFormsAuthenticationService
    {
        void SignIn(string userName, bool createPersistentCookie);

        void SignOut();
    }

    public class FormsAuthenticationService : IFormsAuthenticationService
    {
        public void SignIn(string userName, bool createPersistentCookie)
        {
            if (string.IsNullOrEmpty(userName))
            {
                throw new ArgumentException("Value cannot be null or empty.", "userName");
            }

            FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
        }

        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }
    }
}